#!/usr/bin/env python3
from hashlib import md5
import base64
from Crypto.Cipher import AES

def md5_file(name):
    m = md5()
    a_file = open(name, 'rb')  # 需要使用二进制格式读取文件内容
    m.update(a_file.read())
    a_file.close()
    return m.hexdigest()


'''
采用AES对称加密算法
'''


# str不是32的倍数那就补足为16的倍数
def add_to_32(value):
    while len(value) % 32 != 0:
        value += '\0'
    return str.encode(value)  # 返回bytes


# 加密方法
def encrypt_oracle(key, source_filepath, dst_filepath):
    raw_file = open(source_filepath, 'r')
    encry_file = open(dst_filepath, 'w')

    aes = AES.new(add_to_32(key), AES.MODE_ECB)
    encrypt_aes = aes.encrypt(add_to_32(raw_file.read()))
    encry_file.write(str(base64.encodebytes(encrypt_aes), encoding='utf-8'))

    encry_file.close()
    raw_file.close()
    return 'ok'


# 解密方法
def decrypt_oralce(key, source_filepath, dst_filepath):
    raw_file = open(source_filepath, 'r')
    decry_file = open(dst_filepath, 'w')

    aes = AES.new(add_to_32(key), AES.MODE_ECB)
    base64_decrypted = base64.decodebytes(raw_file.read().encode(encoding='utf-8'))
    decry_file.write(str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', ''))

    decry_file.close()
    raw_file.close()
    return 'ok'


if __name__ == '__main__':
    key = md5_file('temp/flask1.py')
    key1 = "bsos-top"
    key2 = "bsos-topa"
    encrypt_oracle(key1, 'temp/flask1.py', 'temp/flask11.py')
    decrypt_oralce(key2, 'temp/flask11.py', 'temp/flask12.py')
